package sf.core.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.Page;
import com.google.gson.JsonObject;

import sf.core.common.BasePage;
import sf.core.common.DefaultPageList;
import sf.core.exception.SugarException;

/**
 * 处理异常基类
 *
 * @author wb
 */
public class BaseController {

	/**
	 * 处理单独异常
	 *
	 * @param response
	 * @param ex
	 * @throws Exception
	 */
	@ExceptionHandler
	public void exp(HttpServletResponse response, Exception ex) throws Exception {

		ex.printStackTrace();
		if (ex instanceof MissingServletRequestParameterException || ex instanceof NullPointerException) {
			ex.printStackTrace();
			setResponse(HttpServletResponse.SC_BAD_REQUEST, "客户端请求参数有误", response);
		}
		/* 服务异常 */
		else if (ex instanceof SugarException) {
			SugarException exception = (SugarException) ex;
			setResponse(exception.getCode(), ex.getMessage(), response);
		}
		/* 系统异常 */
		else {
			setResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误", response);
		}
	}

	/**
	 *
	 * @param code
	 * @param message
	 * @param response
	 * @throws Exception
	 */
	public void setResponse(int code, String message, HttpServletResponse response) throws Exception {

		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("message", message);
		response.setStatus(code);
		writer.write(jsonObject.toString());
		writer.flush();
		writer.close();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public DefaultPageList createPageList(Page page, List list) throws SugarException {

		BasePage basePage = new BasePage();
		basePage.setPage(page.getPageNum());
		basePage.setLimit(page.getPageSize());
		basePage.setTotalSize(page.getTotal());
		DefaultPageList pageList = new DefaultPageList();
		pageList.setPage(basePage);
		pageList.setList(list);
		return pageList;
	}

	public ModelAndView createModelAndView(String view, Object model) throws SugarException {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(view);
		modelAndView.addObject(model);
		return modelAndView;
	}

}
